package com.hmy.contract.service.contract.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmy.ccp.error.exception.HMYRuntimeException;
import com.hmy.contract.bo.request.contract.ContractInfoListRequest;
import com.hmy.contract.bo.request.contract.ContractSignTaskCancelRequest;
import com.hmy.contract.bo.response.contract.ContractInfoListResponse;
import com.hmy.contract.bo.response.contract.ContractInfoResponse;
import com.hmy.contract.bo.response.contract.ContractSignTaskCancelResponse;
import com.hmy.contract.bo.response.contract.CustomerExtensionResponse;
import com.hmy.contract.bo.response.order.OrderDetailResponse;
import com.hmy.contract.commons.enums.ContractBusinessTypeEnum;
import com.hmy.contract.commons.enums.ContractStatusEnum;
import com.hmy.contract.commons.enums.ContractTypeEnum;
import com.hmy.contract.dal.mapper.ContractMapper;
import com.hmy.contract.dal.po.ContractPo;
import com.hmy.contract.manager.order.OrderFeignClientManager;
import com.hmy.contract.manager.signature.SignatureFeignClientManager;
import com.hmy.contract.service.contract.IContractFeignService;
import com.hmy.contract.service.dto.contract.ContractExtensionFieldDto;
import com.hmy.contract.service.dto.contract.CustomerExtensionDto;
import com.hmy.contract.service.dto.contract.SignTaskDto;
import com.hmy.infrastructure.api.bo.request.signature.SignTaskCancelApiRequest;
import com.hmy.infrastructure.api.bo.response.signature.SignTaskCancelApiResponse;
import com.hmy.order.api.bo.request.OrderListInfoAndSupplyQueryApiRequest;
import com.hmy.order.api.bo.response.OrderPrimaryAndSupplyApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author seven.qi 齐胜南
 * @version 1.0
 * @description
 * @date 2024/3/29 08:40
 */
@Service
@Slf4j
public class ContractFeignServiceImpl extends ServiceImpl<ContractMapper, ContractPo> implements IContractFeignService {

    @Resource
    private OrderFeignClientManager orderFeignClientManager;

    @Resource
    private SignatureFeignClientManager signatureFeignClientManager;


    @Override
    public ContractInfoListResponse contractInfoList(ContractInfoListRequest contractInfoListRequest) {
        LambdaQueryWrapper<ContractPo> wrapper = new LambdaQueryWrapper<>();
        if (CollUtil.isNotEmpty(contractInfoListRequest.getContractIdList())) {
            wrapper.in(ContractPo::getContractId, contractInfoListRequest.getContractIdList());
        }
        if (CollUtil.isNotEmpty(contractInfoListRequest.getStatus())) {
            wrapper.in(ContractPo::getStatus, contractInfoListRequest.getStatus());
        }
        if (StrUtil.isNotEmpty(contractInfoListRequest.getOrderNo())) {
            wrapper.eq(ContractPo::getOrderNo, contractInfoListRequest.getOrderNo());
            wrapper.in(ContractPo::getBusinessType, ContractBusinessTypeEnum.SALE_ELECTRONIC_CONTRACT.getType(), ContractBusinessTypeEnum.SALE_PAPER_CONTRACT.getType());
        }
        if (null != contractInfoListRequest.getOrderId()) {
            wrapper.eq(ContractPo::getOrderId, contractInfoListRequest.getOrderId());
            wrapper.in(ContractPo::getBusinessType, ContractBusinessTypeEnum.SALE_ELECTRONIC_CONTRACT.getType(), ContractBusinessTypeEnum.SALE_PAPER_CONTRACT.getType());
        }
        if (CollUtil.isNotEmpty(contractInfoListRequest.getOrderIdList())) {
            wrapper.in(ContractPo::getOrderId, contractInfoListRequest.getOrderIdList());
            wrapper.in(ContractPo::getBusinessType, ContractBusinessTypeEnum.SALE_ELECTRONIC_CONTRACT.getType(), ContractBusinessTypeEnum.SALE_PAPER_CONTRACT.getType());
        }
        wrapper.eq(ContractPo::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(ContractPo::getCreateTime);
        List<ContractPo> contractPos = this.baseMapper.selectList(wrapper);

        List<ContractInfoResponse> list = new ArrayList<>();
        if (CollUtil.isNotEmpty(contractPos)) {
            contractPos.forEach(contractPo -> {
                ContractInfoResponse contractInfoResponse = new ContractInfoResponse();
                BeanUtil.copyProperties(contractPo, contractInfoResponse, "customerExtension");
                contractInfoResponse.setContractTypeDesc(ContractTypeEnum.getDescByType(contractPo.getContractType()));
                contractInfoResponse.setStatusDesc(ContractStatusEnum.getDescByStatus(contractPo.getStatus()));
                CustomerExtensionDto customerExtensionDto = JSON.parseObject(contractPo.getCustomerExtension(), CustomerExtensionDto.class);
                CustomerExtensionResponse customerExtensionResponse = BeanUtil.copyProperties(customerExtensionDto, CustomerExtensionResponse.class);
                contractInfoResponse.setCustomerExtension(customerExtensionResponse);
                contractInfoResponse.setContacterName(customerExtensionResponse.getCustomerContactorName());
                contractInfoResponse.setCustomerPhone(customerExtensionResponse.getCustomerContactorPhone());
                contractInfoResponse.setCustomerName(customerExtensionResponse.getCustomerName());
                contractInfoResponse.setCustomerId(customerExtensionResponse.getCustomerId());
                contractInfoResponse.setCustomerIdCardNo(customerExtensionResponse.getCustomerContactorIdCardNumber());
                contractInfoResponse.setLessorInfo(contractPo.getLessorInfo());
                contractInfoResponse.setAuthorizerInfo(contractPo.getAuthorizerInfo());
                if (StrUtil.isNotEmpty(contractPo.getContractSignTaskUrl())) {
                    SignTaskDto signTaskDto = JSONUtil.toBean(contractPo.getContractSignTaskUrl(), SignTaskDto.class);
                    contractInfoResponse.setContractSignTaskUrl(signTaskDto.getContractSignTaskUrl());
                }
                if (StrUtil.isNotEmpty(contractPo.getOrderDetailExtension())) {
                    contractInfoResponse.setOrderDetail(JSONUtil.toBean(contractPo.getOrderDetailExtension(), OrderDetailResponse.class));
                }
                list.add(contractInfoResponse);
            });
        }
        ContractInfoListResponse contractInfoListResponse = new ContractInfoListResponse();
        contractInfoListResponse.setContractInfoList(list);
        return contractInfoListResponse;
    }

    @Override
    public ContractSignTaskCancelResponse cancelContractSignTask(ContractSignTaskCancelRequest request) {
        if (request.getContractId() == null) {
            throw new HMYRuntimeException(502000037);
        }
        LambdaQueryWrapper<ContractPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ContractPo::getContractId, request.getContractId());
        ContractPo po = this.getOne(wrapper);
        if (ObjectUtil.isNull(po)) {
            log.error("合同不存在，contractId:{}", request.getContractId());
            throw new HMYRuntimeException(502000002);
        }
        if (po.getIsDeleted()) {
            ContractSignTaskCancelResponse response = new ContractSignTaskCancelResponse();
            response.setSuccess(Boolean.FALSE);
            return response;
        }
        SignTaskCancelApiRequest req = new SignTaskCancelApiRequest();
        req.setContractTaskId(po.getContractTaskId());
        if (StrUtil.isNotEmpty(request.getTerminationNote())) {
            req.setTerminationNote(request.getTerminationNote());
        }
        SignTaskCancelApiResponse resp = signatureFeignClientManager.cancel(req);
        if (!resp.getSuccess()) {
            throw new HMYRuntimeException(502000038);
        }
        // 逻辑删除合同
        ContractPo po1 = new ContractPo();
        if (StrUtil.isNotEmpty(request.getTerminationNote())) {
            ContractExtensionFieldDto contractExtensionFieldDto = new ContractExtensionFieldDto();
            if (Objects.nonNull(JSONUtil.toBean(po.getExtendedFields(), ContractExtensionFieldDto.class))) {
                contractExtensionFieldDto = JSONUtil.toBean(po.getExtendedFields(), ContractExtensionFieldDto.class);
            }
            contractExtensionFieldDto.setTerminationNote(request.getTerminationNote());
            po1.setExtendedFields(JSONUtil.toJsonStr(contractExtensionFieldDto));
        }
        po1.setIsDeleted(Boolean.TRUE);
        LambdaQueryWrapper<ContractPo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(ContractPo::getContractId, po.getContractId());
        this.update(po1, wrapper1);

        ContractSignTaskCancelResponse contractSignTaskCancelResponse = new ContractSignTaskCancelResponse();
        contractSignTaskCancelResponse.setSuccess(Boolean.TRUE);
        return contractSignTaskCancelResponse;
    }
}
